package com.fire.control.system.module.login.controller.app;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fire.control.system.config.redis.RedisService;
import com.fire.control.system.dto.LoginResultDTO;
import com.fire.control.system.dto.UserDTO;
import com.fire.control.system.entity.Role;
import com.fire.control.system.entity.User;
import com.fire.control.system.module.common.controller.BaseController;
import com.fire.control.system.module.login.controller.web.LoginControl;
import com.fire.control.system.module.login.service.ILoginService;
import com.fire.control.system.module.user.service.IUserService;
import com.fire.control.system.standard.BusinessInterfaceStandard;
import com.fire.control.system.statics.Key;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.statics.Type_Role;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.protocol.login.LoginRequestProtocol;

@RestController
@RequestMapping(path = "/app/LoginCtr")
public class AppLoginControl extends BaseController
		implements BusinessInterfaceStandard<LoginRequestProtocol, ResponseProtocol> {
	private static final Log log = LogFactory.getLog(LoginControl.class);
	@Autowired
	private ILoginService loginService;

	@Autowired
	private IUserService userService;

	@Autowired
	private RedisService redisService;

	/**
	 * @author liuxincheng
	 * @Title: loginByIdenCode
	 * @Description: TODO(账号登陆)
	 * @param @param
	 *            requestProtocol
	 * @param @return
	 *            设定文件
	 * @return ResponseProtocol 返回类型
	 * @throws null
	 */
	@RequestMapping(path = "loginByAccount", method = RequestMethod.POST)
	public ResponseProtocol loginByAccount(@RequestBody LoginRequestProtocol requestProtocol,
			HttpServletResponse httpServletResponse) {
		log.info("login (" + requestProtocol.getTaskuuid() + ") task start ...........");
		ResponseProtocol response = loginService.loginByAccount(requestProtocol);

		LoginResultDTO result = (LoginResultDTO) response.getData();

		if (result != null) {
			User user = result.getUser();
			UserDTO userDTO = result.getUserDTO();
			if (user != null) {
				for (Role r : user.getRole()) {
					if (Type_Role.security_patrol.toString().equals(r.getRoleType())) {
						userService.saveUserGetuiInfo(requestProtocol.getCid(), user.getId());
						// 登入成功后首次设置token
						Map<String, Object> returnMap = new HashMap<String, Object>();
						returnMap.put("userId", user.getId());
						returnMap.put(Key.authorization.toString(), userService.createUserToken(user.getId()));

						// 保存用户信息到redis
						redisService.setObject(Key.redis_key_lora_user_id_ + user.getId(), userDTO,
								Key.redis_key_lora_user_id_.getExpire());
						response.setData(returnMap);
						ResponseMessage.CODE_200.messageToProtocol(response).setMessage("登陆成功!");
						System.out.println(1);
					} else {
						ResponseMessage.CODE_400.messageToProtocol(response).setMessage("该权限不允许登陆");
					}
				}
			} else {
				ResponseMessage.CODE_400.messageToProtocol(response).setMessage("该用户不存在");
			}
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("该用户不存在");
		}
		return response;
	}

	/**
	 * @author liuxincheng
	 * @Title: loginBySms
	 * @Description: TODO(发送短信验证码)
	 * @param @param
	 *            resprotocol
	 * @param @return
	 * @param @throws
	 *            Exception 设定文件
	 * @return ResponseProtocol 返回类型
	 * @throws Exception
	 */
	@RequestMapping(path = "/SendSms", method = RequestMethod.POST)
	@ResponseBody
	public ResponseProtocol SendSms(@RequestBody LoginRequestProtocol reqsProtocol) throws Exception {
		log.info("login (" + reqsProtocol.getTaskuuid() + ") task start ...........");
		ResponseProtocol response = loginService.SendSms(reqsProtocol);
		return response;
	}

	/**
	 * @author liuxincheng
	 * @Title: loginBySms
	 * @Description: TODO(短信验证码登陆)
	 * @param @param
	 *            reqsProtocol
	 * @param @return
	 * @param @throws
	 *            Exception 设定文件
	 * @return ResponseProtocol 返回类型
	 * @throws null
	 */
	@RequestMapping(path = "loginBySms", method = RequestMethod.POST)
	@ResponseBody
	public ResponseProtocol loginBySms(@RequestBody LoginRequestProtocol reqsProtocol,
			HttpServletResponse httpServletResponse) throws Exception {
		log.info("login (" + reqsProtocol.getTaskuuid() + ") task start ...........");
		ResponseProtocol response = loginService.LoginBySms(reqsProtocol);
		LoginResultDTO result = (LoginResultDTO) response.getData();
		if (result != null) {
			User user = result.getUser();
			UserDTO userDTO = result.getUserDTO();
			if (user != null) {
				for (Role r : user.getRole()) {
					if (Type_Role.security_patrol.toString().equals(r.getRoleType())) {
						userService.saveUserGetuiInfo(reqsProtocol.getCid(), user.getId());
						// 登入成功后首次设置token
						Map<String, Object> returnMap = new HashMap<String, Object>();
						returnMap.put("userId", user.getId());
						returnMap.put(Key.authorization.toString(), userService.createUserToken(user.getId()));

						// 保存用户信息到redis
						redisService.setObject(Key.redis_key_lora_user_id_ + user.getId(), userDTO,
								Key.redis_key_lora_user_id_.getExpire());
						response.setData(returnMap);
						ResponseMessage.CODE_200.messageToProtocol(response).setMessage("登陆成功!");
						return response;
					} else {
						ResponseMessage.CODE_400.messageToProtocol(response).setMessage("该权限不允许登陆");
					}
				}
			}
		}
		return response;
	}

	/**
	 * @author liuxincheng
	 * @Title: loginOut
	 * @Description: TODO(APP端-->登出系统)
	 * @param @param
	 *            reqsProtocol
	 * @param @return
	 * @param @throws
	 *            Exception 设定文件
	 * @return ResponseProtocol 返回类型
	 * @throws null
	 */
	@RequestMapping(path = "loginOut", method = RequestMethod.POST)
	@ResponseBody
	public ResponseProtocol loginOut(LoginRequestProtocol reqsProtocol) throws Exception {
		reqsProtocol.setTaskuuid(UUID.randomUUID().toString());
		log.info("SendSms (" + reqsProtocol.getTaskuuid() + ") task start ...........");
		ResponseProtocol response = loginService.loginOutApp(reqsProtocol, this.getUser());
		return response;
	}
}
